# -*- coding: utf-8 -*-
import subprocess

from flask import json
import redis
from scrapy_redis.spiders import RedisSpider
from scrapy import Request, FormRequest
from spider.ops import Ops

from facility.time_fn import timestamp2string


# 　反扒
class YidaiyiluSpider(RedisSpider):
    name = 'yidaiyilu'
    redis_key = 'yidaiyilu:start_urls'
    v8host = 'http://localhost:5000/'

    con = redis.Redis(host='localhost', port=6379, db=0)
    con.lpush(redis_key, v8host)

    def parse(self, response):
        yield FormRequest(url='https://www.ydyilu.com/financing/sbtz/index.htm',
                          formdata={
                              'currentPage': "1",
                              'pageSize': '9999',
                              'yearRate': "",
                              'progress': "",
                              'status': "",
                              'orderItem': "",
                              'productId': "",
                          },
                          headers={
                              "Accept": "application/json, text/javascript, */*; q=0.01",
                              "Connection": "keep-alive",
                              "Host": "www.ydyilu.com",
                              "Origin": "https://www.ydyilu.com",
                              "Referer": "https://www.ydyilu.com/financing/sbtz/",
                              "X-Requested-With": "XMLHttpRequest",
                              "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                              "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
                          },
                          dont_filter=True, callback=self.parse_detail)

        # for i in range(1):
        #     yield Request(url='http://localhost:5000/yidaiyilu/{}'.format(i+1), dont_filter=True, callback=self.parse_item)

    # def parse_item(self,response):
    #     q = Ops(response)
    #     for i in range(q.get_num('//*[@id="bidTable"]/tbody/tr')-1):
    #         name =  q.get_attr('//*[@id="bidTable"]/tbody/tr[{}]/td[1]/div/a'.format(i+2),'title')
    #         unit =  q.get_str('//*[@id="bidTable"]/tbody/tr[{}]/td[2]'.format(i+2))
    #         amount =  q.get_str('//*[@id="bidTable"]/tbody/tr[{}]/td[2]/span'.format(i+2))
    #         rate = q.get_str('//*[@id="bidTable"]/tbody/tr[{}]/td[3]/span'.format(i+2))
    #         cycle = q.get_str('//*[@id="bidTable"]/tbody/tr[{}]/td[4]/span'.format(i+2))
    #         c_unit = q.get_str('//*[@id="bidTable"]/tbody/tr[{}]/td[4]'.format(i+2))
    #         data = name+' '+ amount+unit+' '+rate+' '+cycle+c_unit
    #         subprocess.call("echo  {} >>一带一路.txt".format(data), shell=True)

    def parse_detail(self, response):
        q = Ops(response)
        res = q.get_json()['bidList']
        dic = {
            "MYFX": '每月付息,到期还本',
            "YCFQ": "本息到期一次付清"
        }
        for i in res:
            name = i["F04"]
            if "测试" in name: continue
            amount = i["F06"]
            rate = str(i["F07"] * 100) + "%"
            start = timestamp2string(i["F13"])
            cycle = i["F10"]
            way = dic[i["F21"]] if i["F21"] in dic else "本息到期一次付清"
            data = str(name) + " " + str(amount) + " " + str(rate) + " " + str(start) + " " + str(cycle) + " " + str(
                way)
            # print(data)
            subprocess.call("echo  '{}' >>一带一路.txt".format(data), shell=True)
